import { onMounted, ref } from 'vue';
import { QSelect } from 'quasar';

import { request } from 'src/utils';

export interface OptionQueryDto {
  disabled?: boolean;
  search?: string;
  [attr: string]: string | boolean | number | undefined;
}

const optionUrl = '/api/option/';
export function queryOptions(type: string, query?: OptionQueryDto): Promise<SelectOption[]> {
  return request.get(optionUrl + type, { params: query });
}

export const yesNoOptions: SelectOption[] = [
  { label: '是', value: true },
  { label: '否', value: false },
];

export const disableOptions: SelectOption[] = [
  { label: '正常', value: false, color: 'primary' },
  { label: '作废', value: true, color: 'error' },
];

export const genderOptions: SelectOption[] = [
  { label: '男', value: 'M' },
  { label: '女', value: 'F' },
  { label: '保密', value: 'O' },
];

export const menuTypeOptions: SelectOption[] = [
  { label: '模块', value: 1 },
  { label: '菜单', value: 2 },
  { label: '按钮', value: 3 },
];

/**
 * quasar 下拉列表的选项
 * @param loadOptions 加载数据的方法，如果传入，会在Mounted事件中加载数据
 * @returns options,selected,
 */
export function useSelectOptions(loadOptions?: () => Promise<SelectOption[]>) {
  const options = ref<SelectOption[]>();
  const selected = ref<SelectOption | SelectOption[]>();
  if (loadOptions) {
    onMounted(() => loadOptions().then((data) => (options.value = data)));
  }
  return { options, selected };
}

/**
 * quasar 可过滤的下拉列表，懒加载或需要过滤时过滤时加载数据
 * @param loadOptions 加载选项的方法
 * @returns options,selected,filter
 */
export function useSelectFilterOptions(loadOptions: () => Promise<SelectOption[]>, loadOnMounted = false) {
  const { options, selected } = useSelectOptions();

  // 所有选项
  let _options: SelectOption[] | undefined;
  let hasLoadOptions = false;

  if (loadOnMounted) {
    onMounted(() =>
      loadOptions().then((data) => {
        _options = data;
        hasLoadOptions = true;
        options.value = data;
      }),
    );
  }

  const filter = (val: string, update: (callbackFn: () => void, afterFn?: (ref: QSelect) => void) => void) => {
    // 实现懒加载
    if (!hasLoadOptions) {
      loadOptions().then((data) => {
        _options = data;
        hasLoadOptions = true;
        update(() => (options.value = data));
      });
      return;
    }

    //实现过滤
    if (!val || val === '' || val.trim() == '') {
      update(() => (options.value = _options));
      return;
    }
    update(() => {
      const v = val.toLowerCase();
      options.value = _options?.filter((o) => o.label.toLowerCase().indexOf(v) > -1 || (o.data ?? '').toLowerCase().indexOf(v) > -1);
    });
  };

  return { options, selected, filter };
}
